package com.demo.apparel.controller.web;

import com.demo.apparel.common.Result;
import com.demo.apparel.dto.web.AdminLoginDTO;
import com.demo.apparel.dto.web.AdminLoginResponseDTO;
import com.demo.apparel.dto.web.AdminPasswordUpdateDTO;
import com.demo.apparel.dto.web.AdminAddDTO;
import com.demo.apparel.dto.web.AdminWxLoginDTO;
import com.demo.apparel.service.web.AdminService;
import com.demo.apparel.service.web.LogoutService;
import com.demo.apparel.vo.web.AdminVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;


@RestController
@Tag(name = "管理员接口", description = "web管理员登录接口")
@RequestMapping("/web/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private LogoutService logoutService;

    @PostMapping("/login")
    @Operation(summary = "管理员登录")
    public Result<AdminLoginResponseDTO> login(@RequestBody @Valid AdminLoginDTO dto) {
        AdminLoginResponseDTO AdminDTO=adminService.login(dto);
        return Result.success(AdminDTO);
    }

    @PutMapping("/password")
    @Operation(summary = "修改管理员密码")
    public Result<Void> updatePassword(@RequestBody @Valid AdminPasswordUpdateDTO dto,
                                       HttpServletRequest request) {
        String adminId = (String) request.getAttribute("userId");
        adminService.updatePassword(adminId, dto.getOldPassword(), dto.getNewPassword());
        return Result.success();
    }

    //登出登录
    @PostMapping("/logout")
    @Operation(summary = "管理员登出")
    public Result<String> logout(HttpServletRequest request) {
        logoutService.logout(request);
        return Result.success("");
    }

    @GetMapping("/list")
    @Operation(summary = "获取所有管理员")
    public Result<?> getAllAdmins() {
        List<AdminVO> list = adminService.getAllAdminWithInfo();
        return Result.success(list);
    }

    @PostMapping("/add")
    @Operation(summary = "新增管理员")
    public Result<?> addAdmin(@RequestBody AdminAddDTO dto) {
        adminService.addAdmin(dto.getAdmin(), dto.getAdminInfo());
        return Result.success("新增成功");
    }

    @DeleteMapping("/delete/{adminId}")
    @Operation(summary = "删除管理员")
    public Result<?> deleteAdmin(@PathVariable String adminId) {
        adminService.deleteAdmin(adminId);
        return Result.success("删除成功");
    }


    // 生成微信扫码登录 URL
    @GetMapping("/wxLoginQr")
    @Operation(summary = "生成微信扫码登录（需要到企业微信）开发中")
    public Result<String> wxLoginQr() {
        // 这里生成微信扫码登录 URL https://0c5e69cff0a2.ngrok-free.app/wxLoginCallback
        // 注意：redirect_uri 要指向你前端处理扫码回调的地址
        String appId = "wxea4ec594cf3fbb0e";
//        String redirectUri = "http://localhost:8848/wxLoginCallback"; // 前端处理扫码的页面
        String redirectUri = "https://0c5e69cff0a2.ngrok-free.app/wxLoginCallback";
        String state = UUID.randomUUID().toString();

        String qrUrl = "https://open.weixin.qq.com/connect/qrconnect?appid=" + appId
                + "&redirect_uri=" + URLEncoder.encode(redirectUri, StandardCharsets.UTF_8)
                + "&response_type=code&scope=snsapi_login&state=" + state
                + "#wechat_redirect";

        return Result.success(qrUrl);
    }

    @PostMapping("/wxLogin")
    @Operation(summary = "管理员微信扫码登录（需要到企业微信）开发中")
    public Result<AdminLoginResponseDTO> wxLogin(@RequestBody @Valid AdminWxLoginDTO dto) {
        AdminLoginResponseDTO response = adminService.wxLogin(dto.getCode());
        return Result.success(response);
    }

    @PostMapping("/bindWx")
    @Operation(summary = "已登录管理员绑定微信 （需要到企业微信）开发中")
    public Result<Void> bindWx(@RequestBody @Valid AdminWxLoginDTO dto,
                               HttpServletRequest request) {
        String adminId = (String) request.getAttribute("userId"); // 通过 JWT 获取
        adminService.bindWx(adminId, dto.getCode());
        return Result.success();
    }

}
